package com.hhw.controller;

import com.hhw.dao.DepartmentDao;
import com.hhw.dao.EmployeeDao;
import com.hhw.pojo.Department;
import com.hhw.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;
//    员工管理列表查询页面
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }
//    查询所有部门信息
    @RequestMapping("/emp")
    public String toAddpage(Model model){
//        查询所有部门信息
        Collection<Department> departments = departmentDao.getDepartment();
//        输出打印部门内容信息
//        System.out.println(departments);
//        将departments这个对象放入session会话中，便于add.html页面获取
        model.addAttribute("departments",departments);
        return "/emp/add";
    }

//    员工添加操作
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        System.out.println("员工信息:"+employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

//    员工编辑页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(
            @PathVariable("id") Integer id,
            Model model
    ){
//       查询原来的数据
        Employee employeeById = employeeDao.getEmployeeById(id);
//       打印所操作的员工ID值
        System.out.println(employeeById);
//        将id值存入session中
        model.addAttribute("emp",employeeById);
//        查询所有的部门信息
        Collection<Department> departments = departmentDao.getDepartment();
        System.out.println(departments);
        model.addAttribute("departments",departments);
        return "emp/update";
    }
//员工修改功能
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

//根据id进行删除
    @GetMapping("/delemp/{id}")
    public String toDelEmp(@PathVariable("id") Integer id){
    employeeDao.delete(id);
        return "redirect:/emps";
    }

    //注销用户登录
    @RequestMapping("/user/logout")
    public String UserLogout(HttpSession session){
        session.invalidate();
        System.out.println("用户注销登录！");
        return "redirect:/index.html";
    }
}
